import RenderContext from "@/views/cg/lib/RenderContextGame.ts";
import {d3_cube} from "@/views/cg/lib/shape";
import {Mat4} from "@/views/cg/lib/matrix";

export class Robot{
  constructor() {
  }

  __matrix(){
    const tileSize = this.tileSize
    return new Mat4()
      .rotate(0, this.dir+Math.PI*0.5, 0)
      .scale(tileSize/2, tileSize/2, tileSize/2)
      .translate(this.x, -0.6, this.y)
      .getMatrix()
  }
  move(x,y){
    this.x = x
    this.y = y
  }

  turn(dir){
    this.dir = dir
  }

  draw(){
    this.setUnitMatrix(this.__matrix())
    this.updateMatrix()
    super.draw()
  }

  stop(){
    if(this.removeWalk){
      this.removeWalk()
      delete this.removeWalk
    }
  }
  attack(){
    this.clear()
    const timing = RenderContext.getTiming()

    let angle = 0
    this.removeHandle = timing.listen(({diff}) => {
      this.turn(angle)
      this.leftArm.rotate(Math.PI*0.5, 0)
      this.rightArm.rotate(Math.PI*0.5, 0)
      this.leftLeg.rotate(Math.PI*0.5, 0)
      this.rightLeg.rotate(Math.PI*0.5, 0)
      angle += 0.3
    })
  }

  clear(){
    if(this.removeHandle){
      this.removeHandle()
      delete this.removeHandle
    }
    this.turn(0)
    this.leftArm.rotate(0, 0)
    this.rightArm.rotate(0, 0)
    this.leftLeg.rotate(0, 0)
    this.rightLeg.rotate(0, 0)
  }

  walk(){
    this.clear()
    const timing = RenderContext.getTiming()
    let A = 200
    switch (stage){
      case 0:{
        const t= diff % A
        ax = (t/A)*MaxAngle
        break;
      }
      case 1:
      case 2:{
        const t= (diff -A) % (2*A)
        ax = MaxAngle - 2*MaxAngle*(t/(2*A))
        break;
      }
      case 3:{
        const t = (diff - 3*A) % A
        ax = -MaxAngle + MaxAngle*(t/A)
        break;
      }
    }

    this.head.look(ax*0.3)
    this.leftArm.rotate(ax, -Math.PI * 0.1)
    this.leftArm.children[0].rotate(ax*0.1, 0)
    this.rightArm.rotate(-ax, Math.PI*0.1)
    this.rightArm.children[0].rotate(-ax*0.1, 0)
    this.leftLeg.rotate(-ax, 0)
    this.rightLeg.rotate(ax, 0)
  }


}

class Body extends Model{
  constructor(level) {
    const mesh = d3_cube(false,true)
    super(mesh);
    this.name = 'body'
    const mat4 = new Mat4()
    this.setUnitMatrix(
      mat4.scale(0.3,0.5,0.25)
        .getMatrix()
    )
    this.addTextureImage('/texture02.jpg')
  }
}